#include "head.h"
#include <pthread.h>

void *threadFunc(void *argc){
    threadPool_t* threadPool = (threadPool_t *)argc;
    
    while(1){
        // 加锁
        pthread_mutex_lock(&threadPool->mutex);
        while(threadPool->workQueue.len == 0){
            pthread_cond_wait(&threadPool->cond, &threadPool->mutex);
        }
        // 有任务到来
        int clientSockfd = threadPool->workQueue.head->connectfd;
        deQueue(&threadPool->workQueue);
        pthread_mutex_unlock(&threadPool->mutex);
        train_t train;
        bzero(&train, sizeof(train_t));
        recvOrderTrain(clientSockfd, &train);
        // 处理上传和下载
        switch(train.type){
        case GETS:
            printf("GETS start.\n");
            dealGetsOrder(clientSockfd, &train);
            break;
        case PUTS:
            printf("PUTS start.\n");
            dealPutsOrder(clientSockfd, &train);
            break;
        }
    }

    pthread_exit(0);
}

// 功能：创建线程池
int makeWorker(threadPool_t *threadPool, int threadCount){
    // 初始化锁和条件变量
    pthread_mutex_init(&threadPool->mutex, NULL);
    pthread_cond_init(&threadPool->cond, NULL);

    // 线程信息
    threadPool->tidArr.arr = (threadInfo_t *)calloc(threadCount, sizeof(threadInfo_t));

    bzero(&threadPool->workQueue, sizeof(workqueue_t));
    bzero(threadPool->recordUserId, sizeof(int) * 1024);

    for(int i = 0; i < threadCount; i++){
        // 创建子线程
        pthread_t pid;
        pthread_create(&pid, NULL, threadFunc, threadPool);

        // 填充线程相关信息
        threadPool->tidArr.arr[i].threadId = pid;
    }
    return 0;
}

